package pchfserver;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.file.Files;

import javax.activation.MimetypesFileTypeMap;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * 处理http请求
 * @author 854185
 */
public class HttpRequestHandle extends SimpleChannelInboundHandler<FullHttpRequest>{

	private String localDir;
	
	public HttpRequestHandle(String localDir){
		this.localDir = localDir;
	}
	
	public static final HttpVersion HTTP_1_1 = new HttpVersion("HTTP",1,0,true);
	
	@Override
	protected void messageReceived(ChannelHandlerContext paramChannelHandlerContext, FullHttpRequest paramI)
			throws Exception {
		String uri = paramI.uri();
		uri = URLDecoder.decode(uri,"UTF-8");
		String filePath = localDir+uri;
		File file = new File(filePath);
		if(file.isFile()){
			sendFileToClient(paramChannelHandlerContext,file);
			return ;
		}
		paramChannelHandlerContext.close();
	}
	
	/**
	 * 发送文件到客户端
	 * @param ctx
	 * @param file
	 */
	private void sendFileToClient(ChannelHandlerContext ctx, File file){
		try {
			ByteBuf buffer = Unpooled.copiedBuffer(Files.readAllBytes(file.toPath()));
			FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1,HttpResponseStatus.OK,buffer);
			MimetypesFileTypeMap mimeTypeMap = new MimetypesFileTypeMap();
			resp.headers().set(HttpHeaderNames.CONTENT_TYPE,mimeTypeMap.getContentType(file));
			resp.headers().set(HttpHeaderNames.ACCEPT_CHARSET,"");
			ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String getLocalDir() {
		return localDir;
	}
	public void setLocalDir(String localDir) {
		this.localDir = localDir;
	}

}
